//*************************************************************************//
//*           _____   ____________            ______               __     *//
//*          / /__ \ / ____/ ____/           / ____/___  _________/ /     *//
//*     __  / /__/ // __/ / __/    ______   / /_  / __ \/ ___/ __  /      *//
//*    / /_/ // __// /___/ /___   /_____/  / __/ / /_/ / /  / /_/ /       *//
//*    \____//____/_____/_____/           /_/    \____/_/   \__,_/        *//
//*                                                                       *//
//*     Copyright (c) 2006 Ford Argentina. All Rights Reserved.           *//
//*                                                                       *//
//*************************************************************************//

package ar.com.ford.it.webengine.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.MDC;
import ar.com.ford.it.webengine.wslx.WslxUser;

/**
 * MDCUserServletFilter <br>
 * 
 * Filtro que carga el ID del usuario logueado en la aplicacion (o que se esta tratando
 * de loguear) que envia un request, dejandolo disponible para mostrarlo en el
 * log.
 * 
 * @author Aji
 */
public class MDCUserServletFilter implements Filter {

	//private FilterConfig filterConfig = null;

	/**
	 * @see javax.servlet.Filter#init(FilterConfig)
	 */
    public void init(FilterConfig filterConfig) throws ServletException {
    	//this.filterConfig = filterConfig; 		    		
    }


	/**
	 * @see javax.servlet.Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httprequest = (HttpServletRequest) request;
        HttpSession httpsession = httprequest.getSession(false);
        
    	boolean bUserAdded = false;
		String userId = null;

        if  (httpsession != null) {
	        WslxUser user = (WslxUser) httpsession.getAttribute("wslxuser");
	        if (user != null) 
	        	userId = user.getId();
        }

		if (userId == null)
			userId = "unknown";

        MDC.put("wslxuser", userId);
        bUserAdded = true;
        
        try {
            // Continue processing the rest of the filter chain.
            chain.doFilter(request, response);
        }
        finally {
            if (bUserAdded) {
                // Remove the added element again - only if added.
                MDC.remove("wslxuser");
            }
        }
    }

	/**
	 * @see javax.servlet.Filter#destroy()
	 */
    public void destroy() {
    }

}
